package com.xgggh.redpack.ui.home;

import android.os.Bundle;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Lifecycle;

import com.jakewharton.rxbinding3.material.RxBottomNavigationView;
import com.jakewharton.rxbinding3.viewpager.RxViewPager;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.xgggh.redpack.R;
import com.xgggh.redpack.base.ui.BaseActivity;
import com.xgggh.redpack.databinding.ActivityNavHomeBinding;
import com.xgggh.redpack.domain.home.NavHome;
import com.xgggh.redpack.domain.home.NavPersonal;
import com.xgggh.redpack.domain.home.NavRank;
import com.xgggh.redpack.domain.redpack.Pack;
import com.xgggh.redpack.ui.home.viewbinder.NavCreateViewBinder;
import com.xgggh.redpack.ui.home.viewbinder.NavHomeViewBinder;
import com.xgggh.redpack.ui.home.viewbinder.NavRankViewBinder;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;


public class NavHomeActivity extends BaseActivity implements HasSupportFragmentInjector {

    @Inject
    DispatchingAndroidInjector<Fragment> fragmentInjector;

    ActivityNavHomeBinding mBinding;
    Fragment[] fragmentList = new Fragment[]{
            HomeFragment.newInstance(),
            RankFragment.newInstance(),
            CreateFragment.newInstance(),
            ActivityFragment.newInstance(),
            PersonalFragment.newInstance(),
    };

    int[]   nameList  = new int[]{
            R.string.title_home,
            R.string.title_dashboard,
            R.string.title_create,
            R.string.title_activity,
            R.string.title_my,
    };
    private final int mNavMaxIndex=fragmentList.length-1;
    private final int mNavMinIndex=0;

    private final int mNavHomeIndex=mNavMinIndex;
    private final int mNavRankIndex=mNavHomeIndex+1;
    private final int mNavCreateIndex=mNavRankIndex+1;
    private final int mNavActivityIndex=mNavCreateIndex+1;
    private final int mNavPersonalIndex=mNavActivityIndex+1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        mBinding= DataBindingUtil.setContentView(this,R.layout.activity_nav_home);
        super.setSupportActionBarJust(mBinding.toolbar);
        //mBinding.toolbar.setTitle(R.string.app_name);
        mBinding.container.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
        mBinding.container.setOffscreenPageLimit(fragmentList.length);
        mBinding.toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
        RxViewPager.pageSelections(mBinding.container)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(integer -> {
                    int targetPos=integer>mNavMaxIndex?mNavMaxIndex:(integer<mNavMinIndex?mNavMinIndex:integer);
                    mBinding.navigation.getMenu().getItem(targetPos).setChecked(true);
                    mBinding.toolbar.setTitle(nameList[integer]);
                });

        RxBottomNavigationView.itemSelections( mBinding.navigation)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(menuItem -> {
                    switch (menuItem.getItemId()) {
                        case R.id.navigation_home:
                            mBinding.container.setCurrentItem(mNavHomeIndex,true);
                            mBinding.toolbar.setTitle(nameList[mNavHomeIndex]);
                            break;
                        case R.id.navigation_dashboard:
                            mBinding.container.setCurrentItem(mNavRankIndex,true);
                            mBinding.toolbar.setTitle(nameList[mNavRankIndex]);
                            break;
                        case R.id.navigation_create:
                            mBinding.container.setCurrentItem(mNavCreateIndex,true);
                            mBinding.toolbar.setTitle(nameList[mNavCreateIndex]);
                            break;
                        case R.id.navigation_activity:
                            mBinding.container.setCurrentItem(mNavActivityIndex,true);
                            mBinding.toolbar.setTitle(nameList[mNavActivityIndex]);
                            break;
                        case R.id.navigation_my:
                            mBinding.container.setCurrentItem(mNavPersonalIndex,true);
                            mBinding.toolbar.setTitle(nameList[mNavPersonalIndex]);
                            break;
                    }
                });

        //exitApp();
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        //menu.clear();
        //String ss=menu.getItem(0).getTitle().toString();
        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //do it on fragment
        return false;
    }

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return fragmentInjector;
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return fragmentList[i];
        }

        @Override
        public int getCount() {
            return mNavMaxIndex+1;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private Subject mBackClick = PublishSubject.create();

    private void exitApp(){
       mBackClick.mergeWith(mBackClick.debounce(2000, TimeUnit.MILLISECONDS).map((Function<Integer, Integer>) i -> {
            // 两次点击返回间隔大于2s的事件, 用0表示, 区分正常的点击
            return 0;
        }));

       /* mBackClick.mergeWith(mBackClick.debounce(2000, TimeUnit.MILLISECONDS).map((Function<Integer, Integer>) i -> {
            // 两次点击返回间隔大于2s的事件, 用0表示, 区分正常的点击
            return 0;
        }))
                // 这一步转化是关键
                // 使用一个scan转换符去做处理, 如何当前事件是0, 则返回0
                // 否则则是上一个事件加一(这个就可以将所有前后间隔小于2s的事件标上序号, 方便后序订阅处理,
                // 拿到序号1的事件弹出提示, 拿到序号2的序列做返回, 甚至于可以处理3号, 4号),
                // 这样也就可以毫不费力地解决上诉说的要求2秒内点击三次才退出
                // 变成 (1 -> 0 -> 1 -> 0 -> 1 -> 2 -> 3 -> ...)
                .scan((BiFunction<Integer, Integer, Integer>) (prev, cur) -> {
                        if (cur == 0) return 0;
                        return prev + 1;
                    }
                )
                // 过滤掉0, 后面我们只关心拿到的是几号的时间
                .filter((Predicate<Integer>)(v) -> v > 0)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe((Consumer<Integer>) (v) -> {
                    if (v == 1) {
                        Toast.makeText(this, "再按一次退出app", Toast.LENGTH_SHORT).show();
                    } else if (v == 2) {
                        finish();
                    }
                });*/
    }
}
